package cn.ch.pet.service.impl;

import cn.ch.basic.exception.BusinessException;
import cn.ch.basic.service.impl.BaseServiceImpl;
import cn.ch.basic.util.BaiduAuditUtils;
import cn.ch.basic.util.CodeGenerateUtils;
import cn.ch.basic.util.DistanceUtil;
import cn.ch.basic.util.Point;
import cn.ch.org.domain.Shop;
import cn.ch.org.mapper.ShopMapper;
import cn.ch.pet.domain.OrderPetAcquisition;
import cn.ch.pet.domain.Pet;
import cn.ch.pet.domain.SearchMasterMsg;
import cn.ch.pet.domain.SearchMasterMsgAuditLog;
import cn.ch.pet.dto.HandleMsgDto;
import cn.ch.pet.mapper.OrderPetAcquisitionMapper;
import cn.ch.pet.mapper.PetMapper;
import cn.ch.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.ch.pet.mapper.SearchMasterMsgMapper;
import cn.ch.pet.service.ISearchMasterMsgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Why
 * @since 2022-02-27
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;
    @Autowired
    private PetMapper petMapper;

    @Override
    @Transactional
    public void publish(SearchMasterMsg msg) {
        searchMasterMsgMapper.save(msg);
        //1.开启审核，通过百度API的对应接口来检查敏感资源
        //1.1.审核的具体内容
        String test = msg.getTitle() + msg.getAddress() + msg.getName() + msg.getCoatColor();
        //1.2.使用StringBuffer或StringBuilder的方式来存入数据，作为日志信息
        StringBuilder note = new StringBuilder();
        //检验
        if(!BaiduAuditUtils.TextCensor(test)){
            //不合法  一个宠物信息不合法，全部上架失败吗？ 不是，只是当前记录上架失败，其他合法的要成功
            note.append("输入的信息不合法");
        }
        //审核resources -- 由于前端不能使用fastdfs，所以图片资源暂时还不能
        //2.审核不通过
        if(!StringUtils.isEmpty(note.toString())){
            //2.1 消息状态改为驳回 -1
            msg.setState(-1);
            //2.2 保存审核失败日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setAuditTime(new Date());
            log.setMsgId(msg.getId());
            log.setNote("审核失败，请重新录入！");
            log.setState(0);
            searchMasterMsgAuditLogMapper.save(log);
        }else{
            //3.审核通过 设置消息状态为审核通过
            msg.setState(1);
            //添加保存成功日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setAuditTime(new Date());
            log.setMsgId(msg.getId());
            log.setNote("审核通过！");
            log.setState(1);
            searchMasterMsgAuditLogMapper.save(log);
            //3.1 查找50公里内的店铺
            Point point = DistanceUtil.getPoint(msg.getAddress());
            //3.1发布寻主消息的人的点
            Shop nearestShop = DistanceUtil.getNearestShop(point, shopMapper.loadAll());
            if(nearestShop != null){
                //3.1.1 如果找到了。设置寻主消息的shopId（绑定店铺），修改入库;发送短信或邮件，通知店铺
                msg.setShopId(nearestShop.getId());
            }
            //3.1.2 如果找不到。 不设置shopId  不写即可  放入寻主池
        }
        searchMasterMsgMapper.update(msg);
    }


    /**
     * 接单
     *  寻主消息和处理人绑定
     *  生成宠物
     *  生成收购订单
     * @param dto
     */
    @Override
    public void accept(HandleMsgDto dto) {
        //1.判断当前寻主消息，是否已经被接单
        OrderPetAcquisition order = orderPetAcquisitionMapper.loadByMsgIdAndPending(dto.getMsgId());
        if(order != null){
            // 根据寻主消息id查询 查询收购表 且订单状态是：state=0
            throw new BusinessException("哦豁，该消息已经被别人接单！！！");
        }
        //2.没有被接单
        SearchMasterMsg masterMsg = searchMasterMsgMapper.loadById(dto.getMsgId());
        //2.1 生成宠物
        Pet pet = masterMsg2Pet(masterMsg);
        petMapper.save(pet);
        //2.2 生成收购单--绑定操作人
        // alt + shift + m 抽取方法
        order = initOrderPetAcquisition(dto, masterMsg, pet);

        orderPetAcquisitionMapper.save(order);
        //@TODO    给handle人，发送邮件或消息，请它去处理订单
    }

    @Override
    public void reject(Long msgId) {
        //把消息的shopId置空即可
        SearchMasterMsg msg = searchMasterMsgMapper.loadById(msgId);
        msg.setShopId(null);
        searchMasterMsgMapper.update(msg);
    }

    private OrderPetAcquisition initOrderPetAcquisition(HandleMsgDto dto, SearchMasterMsg masterMsg, Pet pet) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        order.setOrderSn(CodeGenerateUtils.generateOrderSn(dto.getHandler()));
        order.setDigest(masterMsg.getName() +":收购单");
        //超时自定取消订单
        order.setLastcomfirmtime(new Date(System.currentTimeMillis() + 1000*60*60*24*2));
        order.setPrice(new BigDecimal(masterMsg.getPrice()));
        order.setPetId(pet.getId());
        order.setUserId(masterMsg.getUserId());
        order.setShopId(masterMsg.getShopId());
        order.setAddress(masterMsg.getAddress());
        order.setEmpId(dto.getHandler());//绑定上门收购宠物的店员
        order.setSearchMasterMsgId(masterMsg.getId());
        return order;
    }

    private Pet masterMsg2Pet(SearchMasterMsg masterMsg) {
        Pet pet = new Pet();
        pet.setName(masterMsg.getName());
        /**
         * saleprice
         * costprice  上门收购宠物之后，确认收购单，来填写价格
         */
        pet.setTypeId(masterMsg.getPetType());
        pet.setShopId(masterMsg.getShopId());
        pet.setSearchMasterMsgId(masterMsg.getId());
        return pet;
    }
}